package com.exam.commonbiz.net.interceptor;

import android.content.Context;
import android.content.pm.PackageManager;

import com.exam.commonbiz.base.BasicApplication;
import com.exam.commonbiz.log.XLog;
import com.exam.commonbiz.util.AppUtil;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;
import okio.Buffer;

/**
 * @Author yuexingxing
 * @time 2020/6/10
 */
public class HeadInterceptor implements Interceptor {

    @Override
    public Response intercept(Chain chain) throws IOException {

        Request.Builder builder = chain.request().newBuilder();
        builder.addHeader("Content-type", "application/json; charset=utf-8");
        builder.addHeader("Accept", "application/json");
        builder.addHeader("User-Agent", "Client/Android V1.0");
        builder.addHeader("Authorization", "Bearer " + BasicApplication.app.getToken());
        builder.addHeader("Api-Version", "1");
        builder.addHeader("App-Version", getVersionName());
        builder.addHeader("Platform", "app");
        builder.addHeader("DeviceId", AppUtil.getIMEI());
        builder.addHeader("Phone-Brand", AppUtil.getBrand());
        builder.addHeader("Phone-Model", AppUtil.getModel());
        builder.addHeader("Phone-Version", AppUtil.getRelease());
        builder.addHeader("wx-time", System.currentTimeMillis() / 1000 + "");

        Request request = builder.build();

        // 打印请求URL和头部
        XLog.d("Retrofit", "URL: " + request.url());
//        XLog.d("Retrofit", "Headers: " + request.headers());

        // 打印请求体（如果有）
        if (request.body() != null) {
            Buffer buffer = new Buffer();
            request.body().writeTo(buffer);
            XLog.d("Retrofit", "Request Body: " + buffer.readUtf8());
        }

        Response response = chain.proceed(request);
        return response;
    }

    //获取版本名
    private String getVersionName() {
        String versionName = "";
        Context context = BasicApplication.app;
        try {
            versionName = context.getPackageManager().getPackageInfo(context.getPackageName(), 0).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }
}
